package com.dmz.etc.server.netty.attr;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import org.springframework.util.CollectionUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能描述: 管理通道Map类
 * @author lee
 */
public class ChannelMatchMap {

    /**
     * 管理一个全局map，保存连接进服务端的通道数量
     */
    private static final ConcurrentHashMap<ChannelId, Channel> CHANNEL_MAP = new ConcurrentHashMap<>(1024);

    public static ConcurrentHashMap<ChannelId, Channel> getChannelMap() {
        return CHANNEL_MAP;
    }

    /**
     * 获取指定name的channel
     */
    public static Channel getClientChannel(ChannelId channelId) {
        if (CollectionUtils.isEmpty(CHANNEL_MAP)) {
            return null;
        }
        return CHANNEL_MAP.get(channelId);
    }


    /**
     * 将channel和对应的name添加到ConcurrentHashMap
     */
    public static void addClientChannel(ChannelId channelId, Channel channel) {
        CHANNEL_MAP.put(channelId, channel);
    }

    /**
     * 移除掉name对应的channel
     */
    public static boolean removeChannel(ChannelId channelId) {
        if (CHANNEL_MAP.containsKey(channelId)) {
            CHANNEL_MAP.remove(channelId);
            return true;
        }
        return false;
    }

}